<script setup lang="ts">
import { headersStore } from '@/stores/apiHeader'
import { baseToolsStore } from '@/stores/baseTools'
import {
  DEFAULT_ECHARTS_FONTSIZE,
  DIALOG_ECHARTS_FONTSIZE,
} from '@/Utils/setting'
import { useDialogStore } from '@/stores/dialog'
const dialogStore = useDialogStore()
const { dialogInfo } = dialogStore

const fontSize = dialogInfo.visible
  ? DIALOG_ECHARTS_FONTSIZE
  : DEFAULT_ECHARTS_FONTSIZE
const dialogInfoVisible = dialogInfo.visible

const isDepartment = computed(() => baseToolsStore().isDepartment) //是否是部门
// 是否为集团总部
const isHeadquarters = computed(() => {
  return headersStore().scope_code === '0000100001'
})
import {
  nextTick,
  onBeforeUnmount,
  onMounted,
  reactive,
  ref,
  watch,
  computed,
} from 'vue'
import * as echarts from 'echarts'

// 调整px到合适的大小
const changePixelSize = (px: number) => {
  // 获取当前屏幕宽度
  const width = document.body.clientWidth
  let res = (px / 1920) * width
  // 保留整数
  return parseInt(res.toFixed(0))
}
const props = defineProps<{
  chartData: any
}>()
props.chartData.name = props.chartData.name + Math.random()

const colors = ['#4153D3', '#8AF6E1', '#FADD69', '#E067E3', '#CC5F30']
const series = computed(() =>
  props.chartData.data?.map((item, index) => {
    return {
      type: 'bar',
      data: item.data.map((dataItem, dataIndex) => ({
        value: dataItem,
        itemStyle: {
          color:
            !isHeadquarters.value && !isDepartment.value
              ? colors[dataIndex]
              : '#4153D3',
        },
      })),
      tooltip: props.chartData.Model
        ? {
            valueFormatter: function (value) {
              return value + ' %'
            },
          }
        : undefined,
      // label: props.chartData.label,
      symbolSize: changePixelSize(7),
      symbol: 'circle',
      barWidth: 16, // 设置柱状图的宽度
    }
  })
)

let option = null
let myChart: echarts.ECharts
const createChart = () => {
  // 判断是否能获取到dom,如果不能直接结束
  const theDom = document.getElementById(props.chartData.name)
  if (!theDom) {
    return ''
  }
  myChart = echarts.init(document.getElementById(props.chartData.name))
  option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'none',
        label: {
          backgroundColor: '#6a7985',
        },
      },
      textStyle: {
        //提示框浮层的文本样式。
        color: '#fff', //文字的颜色。
        fontStyle: 'normal', //文字字体的风格。
        fontWeight: 'normal', // 文字字体的粗细 string [ normal  bold bolder lighter]   number
        fontSize: changePixelSize(fontSize),
      },
      backgroundColor: 'rgba(0,0,0,0.7)',
      position: function (point, params, dom, rect, size) {
        const [pointX, pointY] = point
        const [boxWidth, boxHeight] = size.contentSize
        const x = boxWidth > pointX ? pointX + 10 : pointX - boxWidth - 10
        const y = boxHeight > pointY ? 5 : pointY - boxHeight
        return [x, y]
      },
    },
    legend: [
      {
        itemWidth: changePixelSize(20.2),
        itemHeight: changePixelSize(10.5),
        textStyle: {
          fontSize: changePixelSize(fontSize),
          lineHeight: changePixelSize(15),
          color: '#fff',
        },
      },
    ],
    grid: {
      left: '5%',
      right: '5%',
      top: '13%',
      bottom: '10%',
      containLabel: true, // 是否居中显示图表
    },
    xAxis: {
      type: 'category',
      axisTick: {
        show: false, // 关闭刻度线
      },
      axisLine: {
        show: false, // 关闭轴线
      },
      axisLabel: {
        color: '#fff', // 设置 X 轴标签字体颜色
        interval: 0, // 强制显示所有标签
        fontSize: changePixelSize(fontSize),
        formatter:
          dialogInfoVisible == false
            ? function (str: any) {
                // 中文算2,英文算1,数到maxLength截取,然后打...
                let count = 0
                let result = ''

                for (let i = 0; i < str.length; i++) {
                  const char = str.charAt(i)
                  count += /[\u4E00-\u9FA5]/g.test(char) ? 1.5 : 1

                  if (count > 7) {
                    result += '...'
                    break
                  }

                  result += char
                }
                return result
              }
            : function (str: any) {
                // 中文算2,英文算1,数到maxLength截取,然后打...
                let count = 0
                let result = ''

                for (let i = 0; i < str.length; i++) {
                  const char = str.charAt(i)
                  count += /[\u4E00-\u9FA5]/g.test(char) ? 1.5 : 1

                  if (count > 10) {
                    result += '...'
                    break
                  }

                  result += char
                }
                return result
              },
      },

      data: props.chartData.xAxis.data,
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: '#fff',
        fontSize: changePixelSize(fontSize),
        formatter: props.chartData.Model
          ? function (params) {
              return params + '%'
            }
          : function (params) {
              return params
            },
      },

      splitLine: {
        lineStyle: {
          color: '#123545', // 分割线颜色为灰色
        },
      },
    },
    dataZoom: [
      {
        type: 'inside',
        show: false,
        xAxisIndex: [0],
        zoomOnMouseWheel: false, // 禁止鼠标滚轮缩放
        moveOnMouseWheel: true, // 开启鼠标滚轮窗口平移
        moveOnMouseMove: true, // 开启鼠标移动窗口平移
        throttle: 100, // 限制滑动的频率，单位为毫秒
        start: 0,
        end:
          isHeadquarters.value && isDepartment.value
            ? props.chartData?.xAxis.data.length > 6
              ? ~~((6 / props.chartData?.xAxis.data.length) * 100)
              : 100
            : props.chartData?.xAxis.data.length > 6
            ? ~~((5 / props.chartData?.xAxis.data.length) * 100)
            : 100,

        showDataShadow: false,

        textStyle: {
          color: '#ccd7d7',
        },
      },
    ],
    series: series.value,
  }
  // 绘制图表
  myChart.setOption(option)
}

onMounted(() => {
  nextTick(() => {
    createChart()
  })
})
// 销毁前释放内存
onBeforeUnmount(() => {
  if (myChart) {
    myChart.dispose()
  }
})
watch(
  () => props.chartData,
  () => {
    nextTick(() => {
      createChart()
    })
  },
  { deep: true }
)
</script>

<template>
  <div
    :class="{
      'echart-box': true,
      'dialog-box': dialogInfoVisible == true,
    }"
  >
    <div class="sub-title" v-if="chartData?.subTitle">
      {{ chartData.subTitle }}
      <span>{{ chartData.subTitleVal }}</span>
    </div>
    <div class="chart" :id="chartData.name"></div>
  </div>
</template>

<style lang="scss" scoped>
.echart-box {
  position: relative;
  width: 100%;
  height: calc(260px); // 10px是指示器高度
  display: flex;
  flex-direction: column;
  .chart {
    width: 100%;
    flex: 1;
  }
  .sub-title {
    padding: 10px;
    font-size: 12px;
    span {
      color: #eb6456;
    }
  }
}
.dialog-box {
  height: calc(500px - 45px);
}
</style>
